<?php
/* SVN FILE: $Id: item_pack.php 247 2009-10-22 15:31:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Item Pack item
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 247 $
* @lastrevision $Date: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/items/item_pack.php $
*/

class item_pack extends templateItem
{
	/**
	 * The default name of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultName = "Item Pack";
	
	/**
	 * The default description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultDescription = "Store multiple inventory items in this. Storing: {stored_list}";
	
	// Inherited Properties
	/**
	 * Item setting to allow multiple instances within ibMarket 
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $allowMultiple = true;
	
	/**
	 * Item setting telling that tell what is needed
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $dependcies = array(
									'item'		=> array(),
									'plugin'	=> array(),
									'server'	=> array('ibmarket' => 20000),
								);
	
	/**
	 * Item specific setting
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $itemSettings = array();
	
	/**
	 * Constructor to setup the item
	 *
	 * @access	public
	 * @param	ipsRegistry	$registry	IPB registry
	 * @param	array		&$item		The item information
	 */
	public function __construct(ipsRegistry $registry, array &$item)
	{
		parent::__construct($registry, $item);
		
		if($item['item_config'] || $item['item_id'] != 0)
		{
			$this->itemSettings = unserialize($item['item_config']);
		}
		else
		{
			$this->itemSettings['items'] = array();
			$this->itemSettings['multiple_format'] = '{number}x {item}';
			$this->itemSettings['none'] = 'Nothing';
		}
	}
	
	/**
	 * Additional settings when adding/editing the item
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminForm()
	{
		$form['items'] = marketRegistry::formItemTable('item[items]', $this->itemSettings['items']);
		$form['multiple_format'] = ipsRegistry::getClass('output')->formInput('item[multiple_format]', $this->itemSettings['multiple_format']);
		$form['none'] = ipsRegistry::getClass('output')->formInput('item[none]', $this->itemSettings['none']);
		return <<<EOF
				<li>
					<label>{$this->lang->words['tags_for_description']}</label>
					<div style='display: inline-block'>
						{stored_list} = {$this->lang->words['pack_stored_list']}
						<br />
						{stored_line} = {$this->lang->words['pack_stored_line']}
					</div>
				</li>
				<li>
					<label>
						{$this->lang->words['items_to_store']}
						<span class="desctext">{$this->lang->words['items_to_store_desc']}</span>
					</label>
					<div style='display: inline-block'>
						{$form['items']}
					</div>
				</li>
				<li>
					<label>
						{$this->lang->words['multiple_item_format']}
						<span class="desctext">
							{item} = {$this->lang->words['multiple_item_name']}
							<br />
							{number} = {$this->lang->words['multiple_item_quanity']}
						</span>
					</label>
					{$form['multiple_format']}
				</li>
				<li>
					<label>{$this->lang->words['no_item_in_pack']}</label>
					{$form['none']}
				</li>

EOF;
	}
	
	/**
	 * Saving to adding/editing the item
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	array	[$input]		Relavent input relating to the item
	 * @todo
	 * @return	void
	 */
	public function adminSave(array &$item_info, array $input)
	{
		$setting = array();
		$setting['items'] = marketRegistry::processItemTable(array('item','items'));
		$setting['multiple_format'] = $input['multiple_format'];
		$setting['none'] = $input['none'];
		
		if($setting['items'][$this->item['item_id']] > 0)
		{
			$this->registry->output->showError( $this->lang->words['cannot_include_itself'] );
		}
		
		$item_info['item_config'] = serialize($setting);
	}
	
	/**
	 * When quick saving the price and stock
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	string	$type			Possible values: 'stockprice', more possibly in the future
	 * @return	void
	 */
	public function adminQuickSave(array &$item_info, $type)
	{
		return;
	}
	
	/**
	 * When removing the item from ibMarket
	 *
	 * @access	public
	 * @return	void
	 */
	public function adminRemove()
	{
		return;
	}
	
	/**
	 * Viewing the file edits if any
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminViewFileEdits()
	{
		return false;
	}
	
	/**
	 * Any admin AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function adminAjax()
	{
		return;
	}
	
	/**
	 * Check and modify the intentory item information before storing in the database
	 *
	 * @access	public
	 * @param	array	&$invItem		The new inventory item information to be stored in the database.
	 * @return	bool	true if the item is successfully created, false otherwise
	 */
	public function publicOnCreateItem(array &$invItem)
	{
		if($this->itemSettings['items'])
		{
			$items = array();
			foreach($this->itemSettings['items'] as $itemID => $quanity)
			{
				if(!isset($this->caches['market_items'][$itemID]))
				{
					continue;
				}
				$expired = $this->caches['market_items'][$itemID]['expire_time'] > 0 ? IPS_UNIX_TIME_NOW + $this->caches['market_items'][$itemID]['expire_time'] * $this->caches['market_items'][$itemID]['expire_unit'] : 0;
				for($i = 0; $i < $quanity; $i++)
				{
					$_invItem = array(
										'member_id' => $this->memberData['member_id'],
										'item' => $itemID,
										'price_bought' => $this->caches['market_items'][$itemID]['price'],
										'resell_price' => 0,
										'time_bought' => IPS_UNIX_TIME_NOW,
										'settings' => '',
										'expired' => $expired,
									);
					if(marketRegistry::getItem($this->caches['market_items'][$itemID])->publicOnCreateItem($_invItem))
					{
						$items[] = $_invItem;
					}
				}
			}
			$invItem['settings'] = serialize($items);
		}
		return true;
	}
	
	/**
	 * When using the item
	 * Show a form and validate the form
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	string|bool				string if there is a form to be used, true if successfully used, false otherwise
	 */
	public function publicUseItem(array &$invItem)
	{
		$items = unserialize($invItem['settings']);
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_items' ) );
		
		if($invItem['settings'] && $items)
		{
			// Unpack items
			foreach($items as $k => $item)
			{
				if($item['expired'] && $item['expired'] < IPS_UNIX_TIME_NOW)
				{
					unset($items[$k]);
					continue;
				}
				unset($item['i_id']);
				$this->DB->insert('market_inventory',$item);
			}
			
			if($items)
			{
				$this->deleteItems($invItem);
				
				$this->writeLog($invItem, "Unpacked items");
				
				$this->registry->getClass('output')->redirectScreen( $this->lang->words['items_unpacked'], $this->settings['base_url_with_app'] . "module=inventory" );
			}
		}
		
		$inventoryItems = marketRegistry::getInventoryItem($this->memberData['member_id']);
		unset($inventoryItems[$invItem['i_id']]);
		
		if($this->request['request_method'] == 'post')
		{
			// Pack items
			$items = array();
			$this->request['inv_id'] = is_array($this->request['inv_id']) ? $this->request['inv_id'] : array();
			foreach($this->request['inv_id'] as $i_id)
			{
				if($i_id == $invItem['i_id'] || !isset($inventoryItems[$i_id]))
				{
					continue;
				}
				$items[$i_id] = $inventoryItems[$i_id];
			}
			if(!$items)
			{
				$this->registry->getClass('output')->showError('no_items_packing');
			}
			$setting = serialize(array_values($items));
			
			$this->DB->delete('market_inventory',"i_id IN (".implode(",",array_keys($items)).")");
			$this->DB->update('market_inventory',array(
														'settings' => $setting,
							),"i_id=".$invItem['i_id']);
			
			$this->writeLog($invItem, "Packed items");
			
			$this->registry->getClass('output')->redirectScreen( $this->lang->words['items_packed'], $this->settings['base_url_with_app'] . "module=inventory" );
		}
		
		$rows = array( FALSE, "row1", "row2");
		
		$html = <<<EOF
<form id='itemPackForm' method="post" action="{$this->settings['base_url_with_app']}module=inventory&amp;section=item&amp;item={$invItem['i_id']}">
	<div id='itemPack'class='block_wrap'>
		<h3 id='itemPackHeader' class='maintitle'>{$this->item['item_name']} - {$this->lang->words['pick_items_to_add']}</h3>
		<table class='ipb_table'>
			<tr class='header'>
				<th class='inventoryIcon' scope='col'>{$this->lang->words['inventory_icon']}</th>
				<th class='inventoryName' scope='col'>{$this->lang->words['inventory_name']}/{$this->lang->words['inventory_description']}</th>
				<th class='inventoryCategory' scope='col'>{$this->lang->words['inventory_category']}/{$this->lang->words['inventory_time_bought']}/{$this->lang->words['inventory_expires']}</th>
				<th class='inventoryPrice' scope='col'>{$this->lang->words['inventory_price']}/{$this->lang->words['inventory_resell']}</th>
				<th class='inventoryOption' scope='col'>{$this->lang->words['pack_item']}</th>
			</tr>

EOF;
		if(count($inventoryItems))
		{
			foreach($inventoryItems as $_invItem)
			{
				$class = IPSLib::next( $rows );
				$description = IPSText::getTextClass('bbcode')->preDisplayParse(marketRegistry::getItem($this->caches['market_items'][$_invItem['item']])->parseInventoryDescription($_invItem));
				$timeBought = $this->registry->getClass('class_localization')->getDate($_invItem['time_bought'], "SHORT");
				$expires = numbers::compare($_invItem['expired']) <= 0 ? "<em>".$this->lang->words['never']."</em>" : $this->registry->getClass('class_localization')->getDate($_invItem['expired'], "SHORT" );
				$price = numbers::compare($_invItem['price_bought']) == 0 ? "<em>".$this->lang->words['free']."</em>" : marketFormatter::formatCurrency($_invItem['price_bought']);
				$resell = numbers::compare($_invItem['resell_price']) == 0 ? "<em>".$this->lang->words['trash']."</em>" : marketFormatter::formatCurrency($_invItem['resell_price']);
				$html .= <<<EOF
			<tr class='{$class}'>
				<td class='altrow inventoryIconCell'><img src='{$this->settings['market_images_url']}/icons/{$this->caches['market_items'][$_invItem['item']]['icon']}' alt='{$this->lang->words['icon']}' /></td>
				<td class='inventoryNameCell'>
					<strong>{$this->caches['market_items'][$_invItem['item']]['item_name']}</strong>
					<br />
					{$description}
				</td>
				<td class='altrow oneLine inventoryCategoryCell'>
					{$this->lang->words['inventory_category']}: {$this->caches['market_category'][$this->caches['market_items'][$_invItem['item']]['category']]['cat_name']}
					<br />
					{$this->lang->words['inventory_time_bought']}: {$timeBought}
					<br />
					{$this->lang->words['inventory_expires']}: {$expires}
				</td>
				<td class='oneLine inventoryPriceCell'>
					{$this->lang->words['inventory_price']}: {$price}
					<br />
					{$this->lang->words['inventory_resell']}: {$resell}
				</td>
				<td class='altrow inventoryOptionCell'>
					<input type='checkbox' class='clickable input_submit' name='inv_id[]' value='{$_invItem['i_id']}' />
				</td>
			</tr>

EOF;
			}
		}
		else
		{
			$this->registry->getClass('output')->showError('need_items_to_pack');
		}
		
		$html .= <<<EOF
		</table>
		<fieldset class="submit">
			<input class="input_submit" type="submit" value="{$this->lang->words['pack_items']}" name="submit" />
		</fieldset>
	</div>
</form>
EOF;

		return $html;
	}
	
	/**
	 * Any AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function publicAjax(array &$invItem)
	{
		return;
	}
	
	/**
	 * When the item is being sold back
	 *
	 * @access	public
	 * @param	array	&$invItem	The inventory item information
	 * @return	bool				true if successful, false otherwise
	 */
	public function publicOnResoldItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When the item is being restocked
	 *
	 * @access	public
	 * @param	array	&$item	The inventory item information
	 * @return	void
	 */
	public function onItemRestock(array &$item)
	{
		return;
	}
	
	/**
	 * Get the description of the item, normally called when there is no intentory item being used
	 *
	 * @access	public
	 * @return	string
	 */
	public function parseStoreDescription()
	{
		$items = array();
		foreach($this->itemSettings['items'] as $itemID => $quanity)
		{
			if(!isset($this->caches['market_items'][$itemID]))
			{
				continue;
			}
			if($quanity == 1)
			{
				$items[] = $this->caches['market_items'][$itemID]['item_name'];
			}
			else
			{
				$items[] = str_replace(array('{number}','{item}'),array(marketFormatter::numberFormat($quanity),$this->caches['market_items'][$itemID]['item_name']),$this->itemSettings['multiple_format']);
			}
		}
		if(count($items) == 0)
		{
			$items = array($this->itemSettings['none']);
		}
		return str_replace(array('{stored_list}','{stored_line}'),array("[list][*]".implode("[*]",$items)."[/list]",implode(", ",$items)),$this->item['item_description']);
	}
	
	/**
	 * Get the description of the item, normally called when there is one intentory items being used
	 *
	 * @access	public
	 * @param	array	$invItem	The inventory item information
	 * @return	string
	 */
	public function parseInventoryDescription(array $invItem)
	{
		$items = array();
		$update = false;
		if($invItem['settings'])
		{
			$_items = unserialize($invItem['settings']);
			foreach($_items as $k => $item)
			{
				if($item['expired'] && $item['expired'] < IPS_UNIX_TIME_NOW)
				{
					$update = true;
					unset($_items[$k]);
					continue;
				}
				$items[$item['item']]++;
			}
		}
		if($update)
		{
			$setting = serialize(array_values($_items));
			
			$this->DB->update('market_inventory',array(
														'settings' => $setting,
							),"i_id=".$invItem['i_id']);
		}
		if(count($items) == 0)
		{
			$items = array($this->itemSettings['none']);
		}
		else
		{
			foreach($items as $itemID => $quanity)
			{
				if(!isset($this->caches['market_items'][$itemID]))
				{
					continue;
				}
				if($quanity == 1)
				{
					$items[$itemID] = $this->caches['market_items'][$itemID]['item_name'];
				}
				else
				{
					$items[$itemID] = str_replace(array('{number}','{item}'),array(marketFormatter::numberFormat($quanity),$this->caches['market_items'][$itemID]['item_name']),$this->itemSettings['multiple_format']);
				}
			}
		}
		
		return str_replace(array('{stored_list}','{stored_line}'),array("[list][*]".implode("[*]",$items)."[/list]",implode(", ",$items)),$this->item['item_description']);
	}
}
